let WxParse = require('../../wxParse/wxParse.js');
let app = getApp();
let util= require("../../utils/util.js");
let httptool = require("../../utils/zry.httptool.js");
Page({
  data:{
    param:{},
    forum:{},//帖子数据
    joinCircleName:'',//显示申请加入还是已加入
    replys:[],//评论回复列表
    sendComment:{},//发表评论所需的参数
    isShow: false,//控制emoji表情是否显示
    cfBg: true,
    isLoad: true,//解决初试加载时emoji动画执行一次
    commentArea:true,//评论区域显示否
    replayName:'',//回复框里的回复name
    focus:false,//是否聚焦
    content: "",//评论框的内容
    LikeTimes:'',//点赞数量
    CommentTimes:'',//评论数量
    msgprop:'',//消息提示 
    delForwardArea:true,//转发的帖子被删除后
    showDel:true,
    frompage:0 ,
    delParams:{},//删除评论的参数
    deltype:'',//区分是删除评论的弹框
    delArea:true,//删除提示框
    namemark:'',//从我的评论里跳转过来的评论人名
    ptype: 0,//从我的评论里跳转过来的类型  
    referenceId:0,//编辑有转发内容的帖子--被转发的帖子id
    fromindex:0
  },
    //文本域失去焦点时 事件处理
  textAreaInput: function (e) {
    //获取此时文本域值
    this.setData({
      content: e.detail.value
    });
  },
  onLoad:function(options){
    // 页面初始化 options为页面跳转所带来的参数
    let that=this;
    let param ={};
    param.ID=options.ID;
    param.UserId=app.getStorage('customerId') || '0'; 
    that.setData({ param: param });
    that.getDetailForum();//获取帖子内容
    that.getReplys(0);//获取回复列表
    let namemark=options.namemark;
    let ptype=options.ptype;
    let dtype=options.dtype;
    if(options.replyId){
      let sendComment={};
      sendComment.ReplyId = options.replyId;
      that.setData({ sendComment: sendComment });
    }
    if(ptype==1 || dtype==1){
      that.setData({ replayName: namemark,namemark:namemark,ptype:ptype, focus: true,
       commentArea: false, cfBg: false});
    }
    if (options.fromindex>0){
      that.setData({ fromindex: options.fromindex });
    }
  },
  getDetailForum:function(){//获取帖子详情数据
    let that=this;
    httptool.ajaxBasePost("api/Topic/GetTopicDetail",that.data.param,function(res){
      if(res.suc){
        let data=res.data;
        if (data.Reference!=0 && (data.RefTitile==null || data.RefHeadImg==null)){
            that.setData({delForwardArea:false});
        } else if (data.Reference!=0 && (data.RefTitile!=null || data.RefHeadImg!=null)){
            that.setData({showDel:false});
        }
        if (that.data.fromindex!=1){
          data.IsTops=false;
        }
        that.setData({ forum: data, referenceId: data.Reference});
        that.setData({LikeTimes:that.data.forum.LikeTimes+'+',CommentTimes:that.data.forum.CommentTimes});
        if (that.data.forum.IsAdds == false){
            that.setData({joinCircleName:'已加入'});
        }else if(that.data.forum.IsAdds==true){
          that.setData({joinCircleName:'申请加入'});
        }
        let CreateBy= that.data.forum.CreateBy ;
        let customerId=app.getStorage('customerId');            
      }else{
          app.showNotify(that, res.msg);
      }
    });
  },
  getReplys:function(needSetPrePageData){//获取评论列表
      let that=this;
      httptool.ajaxBasePost("api/TopicReply/GetTopicDetailReplys",that.data.param,function(res){
        if(res.suc){
          let data = app.notNull(res.data, []);
          for(let i=0;i < data.length;i++){
            let date = new Date(data[i].ReplyTime); 
            var m = date.getMonth() + 1;  
            m = m < 10 ? ('0' + m) : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            var h = date.getHours();
            h = h < 10 ? ('0' + h) : h;
            var minute = date.getMinutes();
            minute = minute < 10 ? ('0' + minute) : minute;
            data[i].ReplyTime = m + '-' + d + ' ' + h + ':' + minute;              
          }
          that.setData({replys:data});
          if (needSetPrePageData==1)
            that.setPrePageData(5); 
        }else{
             app.showNotify(that, res.msg);
        }
    });
  },
  thumbs_up:function(e){//点赞事件
    let that=this;
    let thumbs={};
    thumbs.TopicId=e.currentTarget.dataset.id;
    let LikeTimes=that.data.forum.LikeTimes;
    httptool.ajaxPost("api/TopicZan/AddorDelLike",thumbs,function(res){
      if(res.suc){
        let title="";
        if(res.data==1){
          that.setData({LikeTimes:LikeTimes+1});
          that.data.forum.LikeTimes=that.data.LikeTimes;
          title ="点赞成功";
          that.setPrePageData(2);
        }else if(res.data==0){
          title = "取消点赞";
          if(LikeTimes>0){
            that.setData({LikeTimes:LikeTimes-1});
            that.data.forum.LikeTimes=that.data.LikeTimes;
          }else{
            that.setData({LikeTimes:0});
          }
          that.setPrePageData(3);                 
        }
        wx.showToast({
          title: title,
          duration: 1000,
          icon: "success"
        });
      }else{
        app.showNotify(that, res.msg);
      }
    });
  },
  replayComment:function(e){//点击帖子弹出评论
    let that=this;
    let sendComment={};
    let replayName=e.currentTarget.dataset.name;
    // that.startAnimation();
    sendComment.ReplyId=0;// 对帖子回复0
    that.setData({
      commentArea:!that.data.commentArea,
      cfBg:!that.data.cfBg,
      sendComment:sendComment,
      replayName:replayName
    });
  },
  responseSend:function(e){//对别人的评论回复要取帖子评论的id
    let that=this;
    // that.startAnimation();
    let sendComment={};
    let replayName=e.currentTarget.dataset.name;
    sendComment.ReplyId=e.currentTarget.dataset.id;// 对别人的评论回复
    that.setData({commentArea:!that.data.commentArea,sendComment:sendComment,replayName:replayName});
  },   
  //发送评论 事件处理
  send: function () {
    var that = this;
    //此处延迟的原因是 在点发送时 先执行失去文本焦点 再执行的send 事件 此时获取数据不正确 故手动延迟1000毫秒
    that.data.sendComment.TopicId=that.data.param.ID;
    that.data.sendComment.Content=that.data.content;
    console.log(that.data.sendComment.Content);
      if (that.data.content.trim().length > 0) {
        httptool.ajaxPost("api/TopicReply/AddTopicReply", that.data.sendComment, function (res) {
          if (res.suc) {
            let CommentTimes=that.data.CommentTimes;
            that.setData({CommentTimes:CommentTimes+1});
            that.getReplys(1);
            that.setData({
                commentArea:true,
            });
          } else {
               app.showNotify(that, res.msg);
          }
        });
      } else {
        that.setData({
          content: ""//清空文本域值
        })
      }
    that.setData({
        content: ""//清空文本域值
    })
  },
  joinCircle:function(e){//申请加入圈子
    let that=this;
    let circleJoin={};
    circleJoin.ID=that.data.forum.MyCircleId;//我的默认的擂盟id
    circleJoin.UserId=app.getStorage('customerId');
    httptool.ajaxPost("api/Circle/ApplyCircle",circleJoin, function (res) {
        if (res.suc) {
            wx.showToast({
              title: "等待审核",
              duration: 1000,
              icon: "success"
            });
            let forum = that.data.forum;
            forum.IsAdds=0;
            that.setData({ forum: forum });
        } else {
              app.showNotify(that, res.msg);
        }
    });
  },
 delForum:function(e){//删除帖子按钮
     let that=this;
     that.setData({delArea:false});
  },
  delForumaction:function(){//删除帖子
     let that=this;
     let CommentTimes=that.data.forum.CommentTimes;
     let delforums={};
     delforums.ID=that.data.forum.ID;
     httptool.ajaxPost("api/Topic/DelTopic",delforums, function (res) {
      if (res.suc) {
        app.showNotify(that,"删除帖子成功!",function(){
          that.setPrePageData(1);
          wx.navigateBack(); 
        });
      }else{
        app.showNotify(that, res.msg);
      }
    });
  },
    /** 删除帖子时**/
  closeDel:function(e){
    let that=this;
    that.setData({delArea:true});
  },
  canDel:function(e){//取消
    let that=this;
    that.setData({delArea:true});
  },
  delAction:function(e){//确定删除
    let that=this;
    if(that.data.deltype==1){
      that.delReplys();
    }else{
      that.delForumaction();
    }
  },
  /** 删除帖子结束**/
  upTop:function(){//置顶帖子
    let that=this;
    let upForum={};
    upForum.ID=that.data.forum.ID;
    httptool.ajaxPost("api/Topic/AddTopicTop",upForum, function (res) {
      if (res.suc) {
        wx.showToast({
          title: '置顶成功',
          icon: 'success',
          duration: 2000
        })
        that.setPrePageData(4);
        wx.navigateBack();
      }else{
        app.showNotify(that, res.msg);
      }
    });
  },
  delReply:function(e){
    let that=this;
    let deltype=e.currentTarget.dataset.deltype;
    let delParams={};
    delParams.ID=e.currentTarget.dataset.rid;
    that.setData({delParams:delParams,delArea:false,deltype:deltype});
  },
  delReplys:function(e){//删除评论
    let that=this;
    httptool.ajaxPost("api/TopicReply/DelTopicReply",that.data.delParams, function (res) {
      if (res.suc) {
          let datas=res.data;
          let CommentTimes=that.data.CommentTimes;
          that.setData({CommentTimes:CommentTimes-datas,delArea:true});
          that.getReplys(1);
      } else {
        app.showNotify(that, res.msg);
      }
    });
  },
  friendDetail:function(e){//点击头像进入某人的详情页，查看对方信息，帖子
    let that=this;
    let ToUserId=e.currentTarget.dataset.creatid;
    wx.navigateTo({
      url: '/pages/followdetail/followdetail?ToUserId='+ToUserId,
    })
  },
  enterCircle:function(e){//点击擂盟进入对应的擂盟详情
      let id=e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/search/search?ID='+id+"&UserId="+app.getStorage('customerId')+"&eId="+1,
      });
  },
  reSend:function(e){//编辑
    let topicId=e.currentTarget.dataset.id;//帖子id
     wx.navigateTo({
      url: '/pages/share/share?etype='+1+'&topicId='+topicId,
    })
  },
  enterForward:function(e){//点击进入转发页面
    let that=this;
    let fourumId = that.data.referenceId > 0 ? that.data.referenceId:e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/forward/forward?fourumId='+fourumId,
    });
  },
  previewImg:function(e){//预览图片
    let src = e.target.dataset.src;//获取data-src
    let imgLists = e.currentTarget.dataset.list;//获取data-list
    //图片预览
    wx.previewImage({
       current: src, // 当前显示图片的http链接
       urls: imgLists // 需要预览的图片http链接列表
    });
  },
  goToforwardForum:function(e){//点击转发的帖子内容进入对应的帖子详情
    let that=this;
    let forwardId=e.currentTarget.dataset.forumid;
    let retitle = e.currentTarget.dataset.retitle;
    if(forwardId != 0 && retitle != null){
      wx.navigateTo({
        url: '../detailPost/detailPost?ID=' + forwardId +"&retitle="+retitle,
      });
    }else{
      app.showNotify(that, "原贴内容不存了哦，无法查看！");     
    }
  },
  setPrePageData(operatetype){
    //1:删除；2：点赞；3:取消点赞；4：置顶;5:回复；6：删除回复
    let that=this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    let topics = prevPage.data.topics;
    if(topics){
      if (operatetype == 1) {
        for (let i in prevPage.data.topics) {
          if (topics[i].ID == that.data.forum.ID) {
            topics.splice(i, 1);
          }
        }
      } else if (operatetype == 2) {
        for (let i in prevPage.data.topics) {
          if (topics[i].ID == that.data.forum.ID) {
            topics[i].LikeTimes = topics[i].LikeTimes + 1;
          }
        }
      } else if (operatetype == 3) {
        for (let i in prevPage.data.topics) {
          if (topics[i].ID == that.data.forum.ID) {
            topics[i].LikeTimes = topics[i].LikeTimes > 1 ? topics[i].LikeTimes - 1 : 0;
          }
        }
      } else if (operatetype == 4) {
        for (let i in prevPage.data.topics) {
          if (topics[i].ID == that.data.forum.ID) {
            topics.splice(i, 1);
            topics.splice(0, 0, prevPage.data.topics[i]);
          }
        }
      } else if (operatetype == 5) {
        for (let i in prevPage.data.topics) {
          if (topics[i].ID == that.data.forum.ID) {
            topics[i].CommentTimes = that.data.replys.length;
          }
        }
      }

      prevPage.setData({ topics: topics });//更新上一个页面的数据源
    }    
  }  
})
